package org.wx.io.reactor;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @program: my-java
 * @description: selector线程
 * @author: Wang.xun
 * @create: 2021-02-06 20:59
 **/
@Slf4j
public class SelectorThread extends ThreadLocal<LinkedBlockingQueue<Channel>> implements Runnable {
    // 选择器
    Selector selector = null;
    // 每个线程从ThreadLocal取对应Channel队列
    LinkedBlockingQueue<Channel> linkedBlockingQueue = get();

    SelectorThreadGroup stg;

    public SelectorThread(SelectorThreadGroup stg) {
        this.stg = stg;
        try {
            selector = selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected LinkedBlockingQueue<Channel> initialValue() {
        return new LinkedBlockingQueue<>();//你要丰富的是这里！  pool。。。
    }

    @Override
    public void run() {
        while (true){
            try {
                // 阻塞在这
                int num = selector.select();
                if(num>0){ //有事件过来
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        if(key.isAcceptable()){ // 要建立连接
                            acceptHandler(key);
                        }else if(key.isReadable()){
                            readHandler(key);
                        }
                        iterator.remove();
                    }
                }
                // 队列不为空，设置监听的状态
                if(!linkedBlockingQueue.isEmpty()){
                    try {
                        Channel channel = linkedBlockingQueue.take();
                        if(channel instanceof ServerSocketChannel){
                            ((ServerSocketChannel) channel).register(selector,SelectionKey.OP_ACCEPT);
                            log.info("{} register listen",Thread.currentThread().getName());
                        }else if(channel instanceof  SocketChannel){
                            ((SocketChannel) channel).register(selector,SelectionKey.OP_READ,ByteBuffer.allocateDirect(4096));
                            log.info("{} register read",Thread.currentThread().getName());
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    private void acceptHandler(SelectionKey key) throws IOException {
        log.info("{} acceptHandler...",Thread.currentThread().getName());
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        SocketChannel client = serverSocketChannel.accept();
        client.configureBlocking(false);
        stg.nextSelector(client);
    }

    private void readHandler(SelectionKey key) {
        log.info("{} read...",Thread.currentThread().getName());
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // 取出附件
        ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
        byteBuffer.clear();
        while(true){
            // 读取传输
            try {
                int num = socketChannel.read(byteBuffer);
                if(num > 0){
                    // 反转 从写模式到读模式
                    byteBuffer.flip();
                    while(byteBuffer.hasRemaining()){
                        socketChannel.write(byteBuffer);
                    }
                    // 重置标志位信息
                    byteBuffer.clear();

                }else if(num == 0){
                    break;
                }else if(num < 0){
                    log.info("client {} is closed...",socketChannel.getRemoteAddress());
                    socketChannel.close();
                    break;
                }
            } catch (IOException e) {

                try {
                    log.info("client {} is closed...",socketChannel.getRemoteAddress());
                    socketChannel.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                break;
            }
        }
    }

    /**
     * 为boss设置工作selector
     * @param stg
     */
    void setWorker(SelectorThreadGroup stg){
        this.stg = stg;
    }
}
